package geekstudy.week1;


/**
 * 21. 合并两个有序链表
 * https://leetcode-cn.com/problems/merge-two-sorted-lists/comments/
 *
 */
public class Week1MergeTwoSortedLists {

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {


        // 合并 l1 和 l2
        ListNode resultListNode = new ListNode(0);
        ListNode currentNode = resultListNode;
        for(;l1 != null && l2 != null;) {
            if(l1.val < l2.val) {
                currentNode.next = l1;
                currentNode = currentNode.next;
                l1 = l1.next;
            } else {
                currentNode.next = l2;
                currentNode = currentNode.next;
                l2 = l2.next;
            }
        }

        // 先判断为空的情况
        if(l1 == null) {
           currentNode.next = l2;
        }
        if(l2 == null) {
            currentNode.next = l1;
        }

        return resultListNode.next;
    }
}

